<template>
  <el-card>
    <div style="margin-bottom: 20px;">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <DynamicForm ref="formRef" label-width="100px" :form-list="columns">
    </DynamicForm>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "DynamicFormDemo",
};
</script>
<script setup lang="ts">
import { getUserList } from "@/api/user";

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return getUserList(newParams).then((res: any) => {
    res.data?.list.map((item: any) => {
      item.age = item.user.detail.age
    })
    return res.data
  });
};

// 动态表单
const columns = ref([
  {
    prop: "username",
    label: "用户姓名",
    valueType: "input",
    rules: [
    { required: true, message: '用户姓名', trigger: 'blur' },
    ]
  },
  {
    prop: "gender",
    label: "性别",
    // 字典数据
    options: [
      {
        label: "女", value: 1
      },
      {
        label: "男", value: 2
      },
    ],
    valueType: "select",
  },
  {
    prop: "age",
    label: "年龄",
    valueType: "input-number",
  },
  {
    prop: "status",
    label: "用户状态",
    options: [
      { label: "禁用", value: 0 },
      { label: "启用", value: 1 },
    ],
    valueType: "select",
  },
])

const formRef = ref()

const handleAdd = () => {
  formRef.value.addData()
};

const handleReset = () => {
  formRef.value.resetFields()
};
const handleSubmit = () => {
  const list = formRef.value.getData();
  console.log("list: ", list);
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      console.log('valid: ', valid);
    }
  })
};

const init = () => {
  const params = { pageNum: 1, pageSize: 5 }
  getTableList(params).then((res: any) => {
    const { list } = res
    formRef.value.setData(list);
  });
};

onMounted(() => {
  init()
})
</script>

<style scoped>
.table-header {
  margin-bottom: 10px;
}
</style>